package com.sgb.kjwl.view.ui.fragment.device;

import androidx.databinding.DataBindingUtil;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentDeviceList3Binding;
import com.sgb.kjwl.di.device.DaggerDeviceFragComponent;
import com.sgb.kjwl.di.device.DeviceFragModule;
import com.sgb.kjwl.model.entity.lease.LeaseListEntity;
import com.sgb.kjwl.model.entity.request.MachineFilterJson3;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.LeaseEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.house.LeaseCategoryListActivity;
import com.sgb.kjwl.view.ui.adapter.machine.LeaseListAdapter;
import com.sgb.kjwl.view.ui.adapter.machine.LeaseListTopAdapter;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.view.widget.lease.DeviceFliterPopWindow3;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.viewmodel.device.DeviceListFragModel3;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerViewItemDecoration2;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * Description: 机械列表改版3
 * Author zhengkewen
 */
public class DeviceListFragment3 extends AppLazyFragment {
    public static String KEY_TYPE_Id = "typeId";
    public static String KEY_POSITION = "position";
    private static final String FLAG_FILTER = "flag_filter";
    @Inject
    DeviceListFragModel3 viewModel;
    private FragmentDeviceList3Binding binding;
    private String firstCategory = "";
    private String secondCategory = "";

    //    private int position;
    private DictWindow5 classifyWindow;
    private DictWindow5 modelWindow5;

    private List<DictEntity3> modelDictEntityList;
    private DictWindow5 sortWindow;
    private String sortId = "";
    private List<DictEntity3> sortDictEntityList;
    //    private TwoAreaPopWindow2 areaPopWindow;
//    private MultiLevelAreaPopWindow areaWindow;
    private ThreeLevelAreaWindow mAddressPop;
    private List<String> cityList;
    //    private List<BaseAreaEntity<List<BaseAreaEntity>>> areaEntityList;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> areaEntityList;
    private DeviceFliterPopWindow3 popWindow;
    private List<DictEntity3> typeDictEntityList;
    //    private DeviceListActivity3 deviceListActivity3;
    private LeaseListTopAdapter topAdapter;//顶部的adapt
    private LeaseListAdapter adapter;
    private boolean isFirstCheck = false;//是否首次选中

    private int categoryFirst;
    private int categorySecond;
    private boolean isFilter = true;
    private String provinceName = "";
    private String cityName = "";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerDeviceFragComponent.builder()
                .appComponent(appComponent)
                .deviceFragModule(new DeviceFragModule(this))
                .build()
                .inject(this);
    }

    public static DeviceListFragment3 newInstance(String typeId, int position) {
        DeviceListFragment3 fragment = new DeviceListFragment3();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE_Id, typeId);
        bundle.putInt(KEY_POSITION, position);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static DeviceListFragment3 newInstance(String isSelf) {
        DeviceListFragment3 fragment = new DeviceListFragment3();
        Bundle bundle = new Bundle();
        bundle.putString("isSelf", isSelf);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static DeviceListFragment3 newInstance() {
        DeviceListFragment3 fragment = new DeviceListFragment3();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_device_list3, container, false);
        return binding.getRoot();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        checkDismiss(0);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onLazyLoad() {
        initExtra();
        init();
    }

    private void initExtra() {
        if (getArguments() != null) {
            String isSelf = getArguments().getString("isSelf");
            viewModel.filterJson.get().setIsSelf(isSelf);
            categoryFirst = getArguments().getInt("categoryFirst", 0);
            categorySecond = getArguments().getInt("categorySecond", 0);
        }
        if ("1".equals(viewModel.filterJson.get().getIsSelf())) {
            binding.isSelfLayout.setVisibility(View.GONE);
            binding.space.setVisibility(View.VISIBLE);
        } else {
            binding.isSelfLayout.setVisibility(View.VISIBLE);
            binding.space.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initView() {
        binding.classifyLayout.setOnClickListener(this);
        binding.typeLayout.setOnClickListener(this);
        binding.areaLayout.setOnClickListener(this);
        binding.sortLayout.setOnClickListener(this);
        binding.ivFilter.setOnClickListener(this);
        binding.ivMap.setOnClickListener(this);
        binding.isSelfLayout.setOnClickListener(this);
        //机械分类标题点击监听
//        binding.rvConditionSelection.setTabMode(TabLayout.MODE_SCROLLABLE);
//        binding.rvConditionSelection.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
//            @Override
//            public void onTabSelected(TabLayout.Tab tab) {
//                checkDismiss(0);
//                if (isFirstCheck) {
//                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 0, "类型");
//                }
//                isFirstCheck = true;
//                firstCategory = typeDictEntityList.get(tab.getPosition()).getId();
//                viewModel.filterJson.get().setFirstCategoryNo(firstCategory);
//                secondCategory = "";
//                viewModel.filterJson.get().setSecondCategoryNo(secondCategory);
//                viewModel.getMachineModel(false);
//                popWindow.setTypeDefault(classifyWindow.getCheckDefultPosition(firstCategory), firstCategory);
//                viewModel.getFilterModelModel(firstCategory);
//            }
//
//            @Override
//            public void onTabUnselected(TabLayout.Tab tab) {
//
//            }
//
//            @Override
//            public void onTabReselected(TabLayout.Tab tab) {
//
//            }
//        });
//
//
//        binding.tabType.setTabMode(TabLayout.MODE_SCROLLABLE);
//        binding.tabType.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
//            @Override
//            public void onTabSelected(TabLayout.Tab tab) {
//                checkDismiss(0);
//                secondCategory = modelDictEntityList.get(tab.getPosition()).getId();
//                viewModel.filterJson.get().setSecondCategoryNo(secondCategory);////二级设置
//                viewModel.getMachineModel(false);
//                popWindow.setModelDefault(modelWindow5.getCheckDefultPosition(secondCategory), secondCategory);
//                viewModel.getFilterSpec(secondCategory);//重新根据一级目录和二级目录获取对应的属性数据
//            }
//
//            @Override
//            public void onTabUnselected(TabLayout.Tab tab) {
//
//            }
//
//            @Override
//            public void onTabReselected(TabLayout.Tab tab) {
//
//            }
//        });


        if (adapter == null) {
            adapter = new LeaseListAdapter(getActivity(), null);
        }
        adapter.setOnItemClick(new AdapterOnItemClick<LeaseListEntity>() {
            @Override
            public void onItemClick(LeaseListEntity entity, int position) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.getH5Url(entity.getDataId());
                }
            }
        });
        binding.recyclerView.addItemDecoration(new RecyclerViewItemDecoration2(getResources().getDimension(R.dimen.dp10), getResources().getDimension(R.dimen.dp10)));
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        binding.recyclerView.setFootViewText("加载中", "我也是有底线的");
        binding.recyclerView.setAdapter(adapter);

        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getMachineModel(false);
            }

            @Override
            public void onLoadMore() {
                viewModel.getMachineModel(true);
            }
        });

        initFilterView();
    }

    private void initFilterView() {
        //分类选择
        classifyWindow = new DictWindow5(getActivity());
        classifyWindow.setFocusable(false);
        classifyWindow.setOutsideTouchable(false);
        classifyWindow.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                firstCategory = dictEntity.getId();
                viewModel.filterJson.get().setFirstCategoryNo(dictEntity.getId());
                viewModel.getMachineModel(false);
                popWindow.setTypeDefault(classifyWindow.getCheckDefultPosition(dictEntity.getId()), dictEntity.getId());
            }
        });
        classifyWindow.setOnCloseBack(new DictWindow5.OnCloseBack() {
            @Override
            public void dismiss() {
                binding.classifyArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });
        //类型选择
        modelWindow5 = new DictWindow5(getActivity());
        modelWindow5.setFocusable(false);
        modelWindow5.setOutsideTouchable(false);
        modelWindow5.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, dictEntity.getName());
                secondCategory = dictEntity.getId();
                viewModel.filterJson.get().setSecondCategoryNo(secondCategory);
                viewModel.getMachineModel(false);
                popWindow.setModelDefault(modelWindow5.getCheckDefultPosition(dictEntity.getId()), dictEntity.getId());
            }
        });
        modelWindow5.setOnCloseBack(new DictWindow5.OnCloseBack() {
            @Override
            public void dismiss() {
                updateChooseTextStatus(binding.typeLayout, binding.tvType, "类型".equals(binding.tvType.getText()) ? 0 : 2, null);
            }
        });
        sortWindow = new DictWindow5(getActivity());
        sortWindow.setFocusable(true);
        sortWindow.setOutsideTouchable(true);
        sortWindow.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                updateChooseTextStatus(binding.sortLayout, binding.tvSort, 2, dictEntity.getName());
                sortId = dictEntity.getId();
                viewModel.filterJson.get().setSortWay(dictEntity.getId());
                viewModel.getMachineModel(false);
                popWindow.setSortDefault(sortWindow.getCheckDefultPosition(dictEntity.getId()), dictEntity.getId());
            }
        });
        sortWindow.setOnCloseBack(new DictWindow5.OnCloseBack() {
            @Override
            public void dismiss() {
                updateChooseTextStatus(binding.sortLayout, binding.tvSort, "排序".equals(binding.tvSort.getText()) ? 0 : 2, null);
            }
        });

        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setProvinceSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setAreaMore();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnResultClick((key1, key2, key3) -> {
            try {
                List<BaseAreaEntity> listKey1 = (List<BaseAreaEntity>) key1;//省
                List<BaseAreaEntity> listKey2 = (List<BaseAreaEntity>) key2;//市
                List<BaseAreaEntity> listKey3 = (List<BaseAreaEntity>) key3;//区
                viewModel.filterJson.get().setAreaNoList(getCityList(listKey3));
                if (listKey2 != null && listKey2.size() > 0) {
                    cityName = listKey2.get(0).getName();
                    viewModel.filterJson.get().setCityNo(listKey2.get(0).getNo());
                } else {
                    viewModel.filterJson.get().setCityNo("");
                }
                provinceName = listKey1.get(0).getName();
                viewModel.filterJson.get().setProvinceNo(listKey1.get(0).getNo());
                if (!TextUtils.isEmpty(cityName) && "不限".equals(cityName)) {
                    updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, cityName);
                } else {
                    updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, provinceName);
                }
            } catch (Exception exception) {
            }

            viewModel.getMachineModel(false);
        });
        mAddressPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? 0 : 2, null);
            }
        });

//        areaWindow = new MultiLevelAreaPopWindow(getActivity());
//        areaWindow.setBgView(binding.grayLayout);
//        areaWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
//            @Override
//            public void result(Object key1, Object key2, Object key3) {
//                List<BaseAreaEntity> selectedEntities = (List<BaseAreaEntity>) key3;
//                cityList.clear();
//                if (selectedEntities != null) {
//                    for (BaseAreaEntity selected : selectedEntities) {
//                        cityList.add(selected.getNo());
//                    }
//                }
//                viewModel.machineFilterJson3.get().setCityNo(((BaseAreaEntity) key2).getNo());
//                viewModel.machineFilterJson3.get().setDistrictNo(cityList);
//                viewModel.getMachineModel(false);
//                updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, ((BaseAreaEntity) key2).getName());
//            }
//        });
//        areaWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? 0 : 2, null);
//            }
//        });

//        areaPopWindow = new TwoAreaPopWindow2(getActivity());
//        areaPopWindow.setFocusable(false);
//        areaPopWindow.setOutsideTouchable(false);
//        areaPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
//            @Override
//            public void result(Object key1, Object key2, Object key3) {
//                updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, ((ParentAreaEntity) key1).getName());
//                List<ParentAreaEntity> selectedEntities = (List<ParentAreaEntity>) key2;
//                cityList.clear();
//                if (selectedEntities != null) {
//                    for (ParentAreaEntity selected : selectedEntities) {
//                        cityList.add(selected.getNo());
//                    }
//                }
//                viewModel.machineFilterJson3.get().setCityNo(((ParentAreaEntity) key1).getNo());
//                viewModel.machineFilterJson3.get().setDistrictNo(cityList);
//                viewModel.getMachineModel(false);
//            }
//        });
//        areaPopWindow.setOnCloseBack(new TwoAreaPopWindow2.OnCloseBack() {
//            @Override
//            public void dismiss() {
//                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? 0 : 2, null);
//            }
//        });

        popWindow = new DeviceFliterPopWindow3(getActivity());
//        popWindow.setBgView(binding.grayLayout);
        popWindow.setFilterResultClick(new DeviceFliterPopWindow3.FilterResultClick() {
            @Override
            public void result(MachineFilterJson3 filterJson, List<DictEntity3> data, SparseBooleanArray checkBooleanArray) {
                if (TextUtils.isEmpty(filterJson.getSecondCategoryName())) {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, "不限");
                } else {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, filterJson.getSecondCategoryName());
                }
                updateChooseTextStatus(binding.sortLayout, binding.tvSort, 2, filterJson.getSortName());
                viewModel.filterJson.get().setFirstCategoryNo(filterJson.getTypeId());
                viewModel.filterJson.get().setSecondCategoryNo(filterJson.getModelId());
                viewModel.filterJson.get().setSortWay(filterJson.getSortId());
                if (filterJson.getAttrList() == null || filterJson.getAttrList().size() == 0) {
                    viewModel.filterJson.get().setAttributeList(null);
                } else {
                    viewModel.filterJson.get().setAttributeList(filterJson.getAttrList());
                }
                viewModel.getMachineModel(false);

                firstCategory = filterJson.getTypeId();

                secondCategory = filterJson.getModelId();
                modelWindow5.setCheckDefaultById(modelWindow5.getCheckDefultId(secondCategory));

                sortId = filterJson.getSortId();
//                binding.rvConditionSelection.getTabAt(classifyWindow.getCheckDefultPosition(firstCategory)).select();
            }

            @Override
            public void queryTypeChild(String id) {
                viewModel.getFilterModelModel(id);
            }

            @Override
            public void queryNameChild(String id) {
                viewModel.getFilterSpec(id);
            }
        });
    }

    private void init() {
        viewModel.filterJson.get().setProvinceNo(viewModel.getAreaCodeModel());
        cityList = new ArrayList<>();
        viewModel.areaCode.set(viewModel.getAreaCodeModel());
        viewModel.getFilterTypeModel("2");
        viewModel.getMachineModel(false);
    }

    public void showList(List<LeaseListEntity> list, boolean isLoadMore) {
        binding.recyclerView.setNoMore(list.size() < viewModel.pageSize);
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() != 0) {
                adapter.addDatas(list);
            }
        } else {
            if (list.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }

            binding.recyclerView.refreshComplete();
            adapter.setDatas(list);
        }
    }

    public void showTypePopWindow(List<DictEntity3> data) {
        this.typeDictEntityList = data;
        if (data == null || data.size() == 0) {
            return;
        }
        if ("不限".equals(data.get(0).getName().trim())) {
            typeDictEntityList.get(0).setName("全部");
            typeDictEntityList.remove(0);
        }

        int spanCount = 5;
        if (data.size() > 10) {
            spanCount = data.size() / 2;
            if (data.size() % 2 > 0) {
                spanCount += 1;
            }
        }
        topAdapter = new LeaseListTopAdapter(getActivity());
        binding.rvTop.setLayoutManager(new GridLayoutManager(getActivity(), spanCount));
        binding.rvTop.setAdapter(topAdapter);
        topAdapter.setOnItemClick(new AdapterOnItemClick<DictEntity3>() {
            @Override
            public void onItemClick(DictEntity3 bean, int position) {
                LeaseCategoryListActivity.start(getActivity(), "2", bean.getId(), bean.getName());
            }
        });
        topAdapter.clearDatas();
        topAdapter.addDatas(typeDictEntityList);

        popWindow.setTypeData(data);
        popWindow.setTypeDefault(0, "");
    }

//    public void showTypePopWindow(List<DictEntity3> data) {
//        this.typeDictEntityList = data;
//        if (data == null || data.size() == 0) {
//            return;
//        }
//        if (firstCategory == null || firstCategory.equals("")) {
//            firstCategory = data.get(0).getId();
//        }
//        viewModel.getFilterModelModel(firstCategory);
//
//        classifyWindow.setData(data);
//        classifyWindow.setCheckDefaultById(firstCategory);
////        popWindow.setTypeData(data);
////        popWindow.setTypeDefault(classifyWindow.getCheckDefultPosition(typeId), typeId);
//        viewModel.filterJson.get().setFirstCategoryNo(firstCategory);
//
//        if ("不限".equals(data.get(0).getName().trim())) {
//            typeDictEntityList.get(0).setName("全部");
//        }
//
//        for (int i = 0; i < typeDictEntityList.size(); i++) {
//            binding.rvConditionSelection.addTab(binding.rvConditionSelection.newTab().setText(typeDictEntityList.get(i).getName()));
//        }
//        binding.rvConditionSelection.selectTab(binding.rvConditionSelection.getTabAt(categoryFirst));
//    }

    public void showModelPopWindow(List<DictEntity3> data) {
        this.modelDictEntityList = data;
//        if (data == null || data.size() == 0 || !isFilter) {
//            binding.tabType.setVisibility(View.GONE);
//            binding.viewTypeTabLine.setVisibility(View.GONE);
//            return;
//        } else {
//            binding.tabType.setVisibility(View.VISIBLE);
//            binding.viewTypeTabLine.setVisibility(View.VISIBLE);
//        }
//        if (data == null || data.size() == 0) {
//            return;
//        }
        if (TextUtils.isEmpty(secondCategory) && data != null && data.size() > 0) {
            secondCategory = data.get(0).getId();
        }
        modelWindow5.setData(data);
        modelWindow5.setCheckDefaultById(secondCategory);
//        viewModel.filterJson.get().setSecondCategoryNo(secondCategory);
        int position = modelWindow5.getCheckDefultPosition(secondCategory);
        popWindow.setModelData(data);
        popWindow.setModelDefault(position < 0 ? 0 : position, secondCategory);
//
//        //设置类型tab
//        if ("不限".equals(data.get(0).getName().trim())) {
//            data.get(0).setName("全部");
//            if (data.size() == 1) {
//                binding.tabType.setVisibility(View.GONE);
//                binding.viewTypeTabLine.setVisibility(View.GONE);
//                return;
//            } else {
//                binding.tabType.setVisibility(View.VISIBLE);
//                binding.viewTypeTabLine.setVisibility(View.VISIBLE);
//            }
//        }
//
//        binding.tabType.removeAllTabs();
//        for (int i = 0; i < data.size(); i++) {
//            binding.tabType.addTab(binding.tabType.newTab().setText(data.get(i).getName()));
//        }
//        binding.tabType.selectTab(binding.tabType.getTabAt(0));
    }

    public void showSortPopWindow(List<DictEntity3> data) {
        this.sortDictEntityList = data;
        if (data == null || data.size() == 0) {
            return;
        }
        if (sortId == null || sortId.equals("")) {
            sortId = data.get(0).getId();
        }
        sortWindow.setData(data);
        sortWindow.setCheckDefaultById(sortId);
        popWindow.setSortData(data);
        popWindow.setSortDefault(0, data.get(0).getId());
        viewModel.filterJson.get().setSortWay(data.get(0).getId());
    }

//    public void showAreaPop(List<BaseAreaEntity<List<BaseAreaEntity>>> datas) {
//        this.areaEntityList = datas;
//        if (datas == null || datas.size() == 0) return;
//        BaseAreaEntity baseAreaEntity = new BaseAreaEntity();
//        baseAreaEntity.setName("不限");
//        baseAreaEntity.setNo("");
//        baseAreaEntity.setChildren(new ArrayList<>());
//        datas.add(0, baseAreaEntity);
//        for (int i = 0; i < datas.size(); i++) {
//            datas.get(i).getChildren().add(0, baseAreaEntity);
//        }
//        areaWindow.setCityList(datas);
//        areaWindow.setCitySelectType(true);
//        areaWindow.setAreaSelectType(true, false);
//    }

    public void showAddressDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data, String provinceNo) {
        this.areaEntityList = data;
        if (data != null && data.size() > 0) {
            viewModel.filterJson.get().setProvinceNo(provinceNo);
            mAddressPop.setData(data, true, provinceNo);
        }
    }

    public void showFilterSpec(List<DictEntity3> data) {
        viewModel.filterJson.get().setAttributeList(new ArrayList<>());//清空之前的属性参数
        if (data == null) {
            popWindow.setSpecData(new ArrayList<>());
            return;
        }
        popWindow.setSpecData(data);
    }

    @Override
    public void onClick(View v) {
        checkDismiss(v.getId());
        switch (v.getId()) {
            case R.id.classify_layout:
                binding.classifyArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
                classifyWindow.setCheckDefaultById(viewModel.filterJson.get().getFirstCategoryNo());
                classifyWindow.showPopwindow(binding.classifyLayout);
                if (typeDictEntityList == null) {
                    viewModel.getFilterTypeModel("2");
                }
                break;
            case R.id.type_layout:
                updateChooseTextStatus(binding.typeLayout, binding.tvType, "类型".equals(binding.tvType.getText()) ? -1 : 1, null);
                modelWindow5.setCheckDefaultById(viewModel.filterJson.get().getSecondCategoryNo());
                modelWindow5.showPopwindow(binding.typeLayout);
//                if (modelDictEntityList == null) {
                viewModel.getFilterModelModel(firstCategory);
//                }
                break;
            case R.id.area_layout:
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? -1 : 1, null);
                mAddressPop.showPopwindow(binding.areaLayout);
                if (areaEntityList == null) {
                    viewModel.getCityData();
                }
                break;
            case R.id.sort_layout:
                updateChooseTextStatus(binding.sortLayout, binding.tvSort, "排序".equals(binding.tvSort.getText()) ? -1 : 1, null);
                sortWindow.setCheckDefaultById(sortId);
                sortWindow.showPopwindow(binding.sortLayout);
                if (sortDictEntityList == null) {
                    viewModel.getFilterSort();
                }
                break;
            case R.id.iv_filter:
//                popWindow.showPopwindow(binding.filterLayout);
                //2020-12-30 租赁1.4.3需求:出租大厅所有筛选popWindow改为全屏展示
                popWindow.showPopwindowRight(getActivity().getWindow().getDecorView());
                popWindow.backgroundAlpha(0.5f);
                if (typeDictEntityList == null) {
                    viewModel.getFilterTypeModel("2");
                }
//                if (modelDictEntityList == null) {
//                    viewModel.getFilterModelModel(firstCategory);
//                }
                if (sortDictEntityList == null) {
                    viewModel.getFilterSort();
                }
                break;
            case R.id.iv_map:
                startMap();
                break;
            case R.id.isSelf_layout://是否自营
                if (TextUtils.isEmpty(viewModel.filterJson.get().getIsSelf())) {
                    viewModel.filterJson.get().setIsSelf("1");
                    binding.isSelfLayout.setBackgroundResource(R.drawable.search_new_blue_bg);
                    binding.tvIsSelf.setTextColor(getResources().getColor(R.color.red));
                } else {
                    viewModel.filterJson.get().setIsSelf("");
                    binding.isSelfLayout.setBackgroundResource(R.drawable.search_bg);
                    binding.tvIsSelf.setTextColor(getResources().getColor(R.color.color_333333));
                }
                viewModel.getMachineModel(false);
                break;
        }
    }

    private void checkDismiss(int resId) {
        if (classifyWindow != null && classifyWindow.isShowing() && R.id.classify_layout != resId) {
            classifyWindow.dismiss();
        }
        if (modelWindow5 != null && modelWindow5.isShowing() && R.id.type_layout != resId) {
            modelWindow5.dismiss();
        }
        if (mAddressPop != null && mAddressPop.isShowing() && R.id.area_layout != resId) {
            mAddressPop.dismiss();
        }
        if (sortWindow != null && sortWindow.isShowing() && R.id.sort_layout != resId) {
            sortWindow.dismiss();
        }
    }

    //更新选项颜色
    private void updateChooseTextStatus(View view, TextView textView, int value, String name) {
        if (value == 0) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
        } else if (value == -1) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_up_arrow_n, R.color.color_333333);
        } else if (value == 1) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_up_red, R.color.color_main);
        } else if (value == 2) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
        }
        if (TextUtils.isEmpty(name)) return;
        textView.setText(name);
    }

    //设置背景色和图标
    private void setTextViewBg(View view, TextView textView, int bg, int img, int textColor) {
        view.setBackgroundResource(bg);
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }

    private List<String> getCityList(List<BaseAreaEntity> list) {
        cityList = new ArrayList<>();
        for (BaseAreaEntity entity : list) {
            if (!TextUtils.isEmpty(entity.getNo())) {
                cityList.add(entity.getNo());
            }
        }
        return cityList;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LeaseEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_DEVICE_FILTER) {
            String text = (String) event.getMessageData();
            if (TextUtils.isEmpty(text)) text = "";
            viewModel.filterJson.get().setTitle(text);
            viewModel.getMachineModel(false);
        } else if (event.getMessageTag() == EventConstant.EVENT_LEASE_FILTER) {//定位坐标改变后刷新
            viewModel.getMachineModel(false);
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void startMap() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), SelectAddressActivity.class);
        intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
        intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
        intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
        if (!TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData("distance_latitude", ""))) {
            intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(SharedPreferenceUtil.getInstance().getSaveStringData("distance_latitude", "")));
            intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(SharedPreferenceUtil.getInstance().getSaveStringData("distance_longitude", "")));
        }
        startActivityForResult(intent, 255);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 255 && data != null) {
                double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
                double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
                String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
                //保存定位数据,用来给后端传参计算距离
                SharedPreferenceUtil.getInstance().saveData("distance_latitude", String.valueOf(lat));
                SharedPreferenceUtil.getInstance().saveData("distance_longitude", String.valueOf(lon));
                EventBus.getDefault().postSticky(LeaseEvent.make().setMessageTag(EventConstant.EVENT_LEASE_FILTER));
            }
        }
    }

}
